const bcrypt = require('bcryptjs')
const { generateToken } = require('../config/jwt')
const db = require('../config/database')
const { success, error } = require('../utils/responseHelper')

const authController = {
  // 用户注册
  async register(req, res, next) {
    try {
      const { username, password, name, email, role = 'student' } = req.body

      // 检查用户名是否已存在
      const [existingUsers] = await db.execute(
        'SELECT id FROM users WHERE username = ?',
        [username]
      )

      if (existingUsers.length > 0) {
        return error(res, '用户名已存在', 400)
      }

      // 密码加密
      const hashedPassword = await bcrypt.hash(password, 12)

      // 创建用户
      const [result] = await db.execute(
        'INSERT INTO users (username, password, name, email, role) VALUES (?, ?, ?, ?, ?)',
        [username, hashedPassword, name, email, role]
      )

      const user = {
        id: result.insertId,
        username,
        name,
        email,
        role,
      }

      const token = generateToken({ id: user.id, username, role })

      success(res, { user, token }, '注册成功')
    } catch (err) {
      next(err)
    }
  },

  // 用户登录
  async login(req, res, next) {
    try {
      const { username, password } = req.body

      // 查找用户
      const [users] = await db.execute(
        'SELECT id, username, password, name, email, role FROM users WHERE username = ?',
        [username]
      )

      if (users.length === 0) {
        return error(res, '用户名或密码错误', 401)
      }

      const user = users[0]

      // 验证密码
      const isValidPassword = await bcrypt.compare(password, user.password)
      if (!isValidPassword) {
        return error(res, '用户名或密码错误', 401)
      }

      // 生成令牌
      const token = generateToken({
        id: user.id,
        username: user.username,
        role: user.role,
      })

      // 返回用户信息（不包含密码）
      const { password: _, ...userInfo } = user

      success(res, { user: userInfo, token }, '登录成功')
    } catch (err) {
      next(err)
    }
  },

  // 获取当前用户信息
  async getCurrentUser(req, res, next) {
    try {
      const [users] = await db.execute(
        'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
        [req.user.id]
      )

      if (users.length === 0) {
        return error(res, '用户不存在', 404)
      }

      success(res, users[0])
    } catch (err) {
      next(err)
    }
  },

  // 修改密码
  async changePassword(req, res, next) {
    try {
      const { oldPassword, newPassword } = req.body
      const userId = req.user.id

      // 验证旧密码
      const [users] = await db.execute(
        'SELECT password FROM users WHERE id = ?',
        [userId]
      )

      const isValidOldPassword = await bcrypt.compare(
        oldPassword,
        users[0].password
      )
      if (!isValidOldPassword) {
        return error(res, '原密码错误', 400)
      }

      // 更新密码
      const hashedNewPassword = await bcrypt.hash(newPassword, 12)
      await db.execute('UPDATE users SET password = ? WHERE id = ?', [
        hashedNewPassword,
        userId,
      ])

      success(res, null, '密码修改成功')
    } catch (err) {
      next(err)
    }
  },
}

module.exports = authController
